//
//  QKTSQLite.cpp
//  Chart
//
//  Created by CaoJun on 15-9-14.
//
//

#include "QKTSQLite.h"
#include "YTXChartTools.h"

#import <Foundation/Foundation.h>

using namespace ytx;
using namespace std;

QKTSQLite::QKTSQLite() : BaseSQLite(){
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = paths[0];
    NSString *fileName = [NSString stringWithFormat:@"%@/QKTData.rdb", documentsDirectory];
    path = [fileName UTF8String];
}

QKTSQLite::~QKTSQLite(){
    sqlite3_close(sqliteDB);
}

bool QKTSQLite::getDataFromDB(string tableName, vector<QKTItem> * qkItems)
{
    if(openDB())
    {
        DBResult dbResult;
        dbResult.status = false;
        char * errmsg = 0;
        const string queryStr = "SELECT * FROM "+ tableName + " ORDER BY tradedatepre DESC";
        int ret = sqlite3_exec(sqliteDB, queryStr.c_str(), handelr_exec, &dbResult, &errmsg);
        CheckResult(ret, errmsg);
        CheckDBResult(dbResult, "getDataFromDB");
        (*qkItems) = transforDataQKT(dbResult);
        sqlite3_close(sqliteDB);
        return true;

    }
    sqlite3_close(sqliteDB);
    return false;
}

vector<QKTItem> QKTSQLite::transforDataQKT(DBResult & dbResult)
{
    vector<QKTItem> result;
    YTXTime tradedatepre;
    int type;
    YTXTime tradedatenext;

    unsigned int index = 0;
    size_t size = dbResult.row_value.size() - 1;
    //有多少列是确定的
    for (vector<vector <string> >::reverse_iterator it =  dbResult.row_value.rbegin(); it != dbResult.row_value.rend(); ++it) {
        index = (unsigned int)(size - (it-dbResult.row_value.rbegin()));
        tradedatepre = YTXTime( Tools::parseLong( dbResult.getValue(index, 0) ) );
        type = Tools::parseInt( dbResult.getValue(index, 1) );
        tradedatenext = YTXTime( Tools::parseLong( dbResult.getValue(index, 2) ) );

        QKTItem qk = {
            tradedatepre,
            (QKTType::QKTType)type,
            tradedatenext
        };

        result.push_back(qk);
    }

    return result;
}


bool QKTSQLite::insertData(string tableName, vector<QKTItem> dataList)
{
    if (openDB())
    {
        char * errmsg = 0;
        sqlite3_exec(sqliteDB, "begin;", 0, 0, 0);

        for (vector<QKTItem>::iterator iter = dataList.begin() ; iter != dataList.end() ; iter++ )
        {
            QKTItem data = (*iter);
            const string sqlStr = "INSERT INTO "+ tableName +" (tradedatepre, type, tradedatenext) VALUES("+ ConvertToString(data.tradedatepre.getCurrentTime()) + "," + ConvertToString(data.type) + "," + ConvertToString(data.tradedatenext.getCurrentTime()) + ")";
            int ret = sqlite3_exec(sqliteDB, sqlStr.c_str(), 0, 0, &errmsg);
            ContinueResult(ret, errmsg);
        }
        sqlite3_exec(sqliteDB, "commit;", 0, 0, 0);
        sqlite3_close(sqliteDB);
        return true;
    }
    return false;
}

bool QKTSQLite::updateData(string tableName, QKTItem item)
{
    if (openDB())
    {
        char * errmsg = 0;
        sqlite3_exec(sqliteDB, "begin;", 0, 0, 0);

        const string sqlStr = "UPDATE "+ tableName + " SET tradedatenext = " +  ConvertToString(item.tradedatenext.getCurrentTime()) + " WHERE tradedatepre = " + ConvertToString(item.tradedatepre.getCurrentTime());
        int ret = sqlite3_exec(sqliteDB, sqlStr.c_str(), 0, 0, &errmsg);

        sqlite3_exec(sqliteDB, "commit;", 0, 0, 0);
        sqlite3_close(sqliteDB);
        CheckResult(ret, errmsg);
        return true;
    }
    return false;
}

bool QKTSQLite::createQKTDataTableIfNotExit(const string tableName){
    //    sqlite3_stmt *stmt = NULL;
//    sqlite3 * sqliteDB = getDB(path, false);
    if (openDB()){
        char * errmsg = 0;
        int ret;
        const string hasTbaleSQL = "SELECT COUNT(*) FROM sqlite_master where type='table' AND name='"+tableName+"'";

        DBResult dbResult;
        dbResult.status = false;

        ret = sqlite3_exec(sqliteDB,hasTbaleSQL.c_str(), handelr_exec, &dbResult, &errmsg);

        CheckResult(ret, errmsg);

        if (Tools::parseInt(dbResult.getValue(0, 0)) > 0) {
            return true;
        }

        const string createTableSQL =
            "CREATE TABLE "+ tableName +" (\
            tradedatepre REAL PRIMARY KEY NOT NULL UNIQUE,\
            type INTEGER,\
            tradedatenext REAL\
        )";

        ret = sqlite3_exec(sqliteDB,createTableSQL.c_str(), handelr_exec, &dbResult, &errmsg);

        CheckResult(ret, errmsg);

//        sqlite3_close(sqliteDB);
        return true;
    }

    sqlite3_close(sqliteDB);
    return false;
}

bool QKTSQLite::vacuumDB()
{
    if (openDB())
    {
        char * errmsg = 0;
        int ret;
        const string hasTbaleSQL = "VACUUM";
        
        DBResult dbResult;
        dbResult.status = false;
        
        ret = sqlite3_exec(sqliteDB,hasTbaleSQL.c_str(), BaseSQLite::handelr_exec, &dbResult, &errmsg);
        
        CheckResult(ret, errmsg);
        return true;
    }
    sqlite3_close(sqliteDB);
    return false;
}